import { memo,isValidElement, useEffect } from 'react'
import { withRouter } from 'next/router'
import { connect } from 'react-redux'
import Link from  'next/link'
import { Col, Row, List, Pagination } from 'antd'
import { request }  from '../lib/dealRquest'
import Repo from '../components/Repo'
import { cacheArray } from '../lib/repo-basic-cache'
const LANGUAGES = ['JavaScript', 'HTML', 'CSS', 'TypeScript', 'Java', 'Python']
const SORT_TYPES = [
  {
    name: 'Best match',
  },
  {
    name: 'Most stars',
    value: 'stars',
    order: 'desc',
  },
  {
    name: 'Fewest stars',
    value: 'stars',
    order: 'asc',
  },
  {
    name: 'Most forks',
    value: 'forks',
    order: 'desc',
  },
  {
    name: 'Fewest forks',
    value: 'forks',
    order: 'asc',
  },
]

const selectItemStyle = {
  borderLeft: '2px solid #e36209',
  fontWeight: 100
}
const per_page = 20

const isServer = typeof window  === 'undefined'

const FilterLink = memo(({ name, query, lang, sort, order, page}) => {
  //设置路由
  let queryString = `?q=${query}`
  if(lang) queryString += `&lang=${lang}`
  if (sort) queryString += `&sort=${sort}&oder=${order || 'desc'}`
  if (page) queryString += `&page=${page}`
  queryString += `&per_page=${per_page}`
  
  return (
    <Link href={`/search${queryString}`}>
      {isValidElement(name) ? name : <a>{name}</a>}
    </Link>
  )
})

const noop = () => {}

const Search = ({ router,repos }) => {
  const { ...querys } = router.query
  const { lang, sort, order, page } = router.query
  //设置缓存
  useEffect(() => {
    if (!isServer) cacheArray(repos.items)
  })
  return (
    <div className="root">
      <Row gutter={24}>
        <Col span={4}>
          <List
            style={{ marginBottom: 20, marginTop: 20}}
            bordered
            header={<span className="list-header">语言</span>}
            dataSource={LANGUAGES}
            renderItem={(item) => {
              const selected = lang === item
              return(
                <List.Item style={selected? selectItemStyle : null}>
                  { selected ?
                    <span>{item}</span>
                    : <FilterLink
                      { ...querys }
                      lang={item}
                      name={item}/>
                  }
                </List.Item>
              )
            }}
            />
          <List
            className="sort-list"
            bordered
            header={<span className="list-header">排序</span>}
            dataSource={SORT_TYPES}
            renderItem={(item) => {
              let  selected = false
              if(item.name === 'Best Match' && !sort) {
                selected = true
              } else if (item.value === sort && item.order === order) {
                selected = true
              }
              return(
                <List.Item style={ selected? selectItemStyle : null}>
                  {
                    selected ?
                    <span>{item.name}</span>
                    : <FilterLink
                        { ...querys }
                        sort={item.value}
                        order={item.order}
                        name={item.name} />
                  }
                </List.Item>
              )
            }}
          />
        </Col>
        <Col span={20}>
          <h3 className="repos-title">{repos.total_count}个仓库</h3>
          {
            repos ? repos.items.map(repo => ( <Repo repo={repo} key={repo.id} />)) : null
          }
          <div className="pagination">
            <Pagination
              pageSize={ per_page }
              current={Number(page) || 1}
              total={1000}
              onChange={noop}
              itemRender={(page, type, ol) => {
                const p = type === 'page' ? page : type === 'prev' ? page - 1 : page + 1
                const name = type === 'page' ? page : ol
                return <FilterLink {...querys} page={p} name={name} />
              }}
            />
          </div>
        </Col>
      </Row>
      <style jsx>{`
        .list-header {
          font-weight: 800;
          font-size: 16px;
        }
        .repo-title {
          border-bottom: 1px solid #eee;
          font-size: 24px;
          line-height: 50px;
        }
        .pagination {
          padding: 20px;
          text-align: right;
        }
      `}</style>
    </div>
  )
}

Search.getInitialProps = async (ctx) => {
  const { query, lang, sort, order, page} = ctx.query
  let queryString = `?q=${query}`
  if(lang) queryString += `+lang:${lang}`
  if (sort) queryString += `&sort=${sort}&oder=${order || 'desc'}`
  if (page) queryString += `&page=${page}`
  queryString += `&per_page=${per_page}`
  const result = await request({
    url: `/search/repositories${queryString}`
  },ctx.req, ctx.res)
  return {
    repos: result.data
  }
  
}
export default connect( state => state)(withRouter(Search))
